package com.java80.littlegame.service.room;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.java80.littlegame.common.base.BaseHandler;
import com.java80.littlegame.common.base.GameUser;
import com.java80.littlegame.common.base.ServiceStatusHelper;
import com.java80.littlegame.common.base.SystemConsts;
import com.java80.littlegame.common.base.SystemDataMgr;
import com.java80.littlegame.common.base.VertxMessageHelper;
import com.java80.littlegame.common.db.dao.DAOFactory;
import com.java80.littlegame.common.db.dao.URoomInfoDao;
import com.java80.littlegame.common.db.dao.UUserInfoDao;
import com.java80.littlegame.common.db.dao.UUserRoomInfoDao;
import com.java80.littlegame.common.db.entity.SGameConfig;
import com.java80.littlegame.common.db.entity.SGameInfo;
import com.java80.littlegame.common.db.entity.URoomInfo;
import com.java80.littlegame.common.db.entity.UUserInfo;
import com.java80.littlegame.common.db.entity.UUserRoomInfo;
import com.java80.littlegame.common.message.proto.BaseMsg;
import com.java80.littlegame.common.message.proto.ProtoHelper;
import com.java80.littlegame.common.message.proto.ProtoList;
import com.java80.littlegame.common.message.proto.cluster.GameStartMessage;
import com.java80.littlegame.common.message.proto.room.CreateRoomMessage;
import com.java80.littlegame.common.message.proto.room.JoinRoomMessage;
import com.java80.littlegame.common.message.proto.room.UserJoinRoomMessage;
import com.java80.littlegame.common.message.proto.room.UserJoinRoomMessage.PlayerInfo;
import com.java80.littlegame.common.utils.RandomUtils;

public class RoomHandler extends BaseHandler {
	final transient static Logger log = LoggerFactory.getLogger(RoomHandler.class);

	@Override
	public Object onReceive(String obj) {
		if (obj instanceof String) {
			onMessage(ProtoHelper.parseJSON(obj.toString()));
		}
		return null;
	}

	private void onMessage(BaseMsg msg) {
		switch (msg.getCode()) {
		case ProtoList.MSG_CODE_CREATE_ROOM:
			createRoom((CreateRoomMessage) msg);
			break;
		case ProtoList.MSG_CODE_JION_ROOM:
			joinRoom((JoinRoomMessage) msg);
		default:
			break;
		}
	}

	private void joinRoom(JoinRoomMessage msg) {
		long userId = msg.getSenderUserId();
		int roomId = msg.getRoomId();

		URoomInfoDao rdao = DAOFactory.getRoomInfoDao();
		UUserRoomInfoDao urdao = DAOFactory.getUserRoomInfoDao();
		TreeMap<Integer, SGameConfig> gameConfigs = SystemDataMgr.getGameConfigs();
		List<UUserRoomInfo> allUserInRoom = null;
		URoomInfo uRoomInfo = rdao.get(roomId);
		int result = 0;
		boolean startgame = false, pwdcheck = false, statusCheck = false, inRoomCheck = false;
		List<PlayerInfo> playerInfos = null;
		if (uRoomInfo != null) {
			if (uRoomInfo.getPassword() != null && uRoomInfo.getPassword() != 0) {
				if (uRoomInfo.getPassword() == msg.getPassword()) {
					// 密码对
					pwdcheck = true;
				}
			} else {
				// 无密码
				pwdcheck = true;
			}
			statusCheck = uRoomInfo.getStatus() == 0;
			List<UUserRoomInfo> allByUserId = urdao.getAllByUserId(userId);
			if (allByUserId == null || allByUserId.isEmpty()) {
				inRoomCheck = true;
			} else if (allByUserId.size() == 1 && allByUserId.get(0).getRoomId() == roomId) {
				inRoomCheck = true;
			}
			if (pwdcheck && statusCheck && inRoomCheck) {
				result = 1;
				Integer gameId = uRoomInfo.getGameId();
				UUserRoomInfo ur = new UUserRoomInfo();
				ur.setCreateTime(new Date());
				ur.setGameId(gameId);
				ur.setRoomId(roomId);
				ur.setUserId(userId);
				urdao.insert(ur);

				msg.setGameId(gameId);
				playerInfos = new ArrayList<>();
				UUserInfoDao userInfoDao = DAOFactory.getUserInfoDao();
				allUserInRoom = urdao.findByRoomId(roomId);
				for (UUserRoomInfo i : allUserInRoom) {
					PlayerInfo pi = new PlayerInfo();
					pi.setId(i.getUserId());
					UUserInfo info = userInfoDao.get(i.getUserId());
					pi.setNickName(info.getNickName());
					playerInfos.add(pi);
				}

				SGameConfig sGameConfig = gameConfigs.get(gameId);
				int playerSum = sGameConfig.getPlayerSum();
				if (allUserInRoom.size() == playerSum) {
					// 开局消息
					// addTask(this, obj);
					startgame = true;
				}
			} else {
				if (!pwdcheck) {
					result = -1;
				}
				if (!statusCheck) {
					result = -2;
				}
				if (!inRoomCheck) {
					result = -3;
				}
			}
		} else {
			result = 0;
		}
		msg.setResult(result);
		GameUser gameUser = GameUser.getGameUser(userId);
		if (gameUser != null) {
			VertxMessageHelper.sendMessageToGateWay(gameUser, msg);
		}
		if (result == 1) {
			// 通知其他人 有人加入
			for (PlayerInfo p : playerInfos) {
				UserJoinRoomMessage jm = new UserJoinRoomMessage();
				jm.setJoinUserId(msg.getSenderUserId());
				jm.setPlayers(playerInfos);
				jm.setRecUserId(p.getId());
				VertxMessageHelper.sendMessageToGateWay(GameUser.getGameUser(p.getId()), jm);
			}

		}
		if (startgame) {
			//

			gameUser.setGameServiceId(
					ServiceStatusHelper.randServiceStatus(SystemConsts.SERVICE_TYPE_GAME).getServiceId());
			gameUser.save();
			// TODO 开局 锁定房间
			for (UUserRoomInfo ur : allUserInRoom) {
				GameUser user = GameUser.getGameUser(ur.getUserId());
				if (!user.equals(gameUser)) {
					user.setGameServiceId(gameUser.getGameServiceId());
					user.save();
				}
			}
			GameStartMessage gsm = new GameStartMessage();
			gsm.setGameId(msg.getGameId());
			gsm.setRoomId(roomId);

			VertxMessageHelper.sendMessageToGame(gameUser, gsm);
		}
	}

	private void createRoom(CreateRoomMessage msg) {
		// 创建房间
		long userId = msg.getSenderUserId();
		// 先查询此人有没有房间 或者有其他房间没解散的
		UUserRoomInfoDao dao1 = DAOFactory.getUserRoomInfoDao();
		URoomInfoDao dao2 = DAOFactory.getRoomInfoDao();
		List<UUserRoomInfo> list1 = dao1.getAllByUserId(userId);
		List<URoomInfo> list2 = dao2.getAllByUserId(userId);
		if ((list1 != null && !list1.isEmpty()) || (list2 != null && !list2.isEmpty())) {
			msg.setResult(-1);
			log.info("玩家{}已存在房间", userId);
		} else {
			int gameId = msg.getGameId();
			TreeMap<Integer, SGameInfo> gameInfos = SystemDataMgr.getGameInfos();
			TreeMap<Integer, SGameConfig> gameConfigs = SystemDataMgr.getGameConfigs();
			SGameConfig cfg = gameConfigs.get(gameId);
			SGameInfo gameInfo = gameInfos.get(gameId);
			if (cfg == null || gameInfo == null) {
				log.info("游戏配置不存在，{}", gameId);
				msg.setResult(-2);
			} else {
				// 先查询生成的gameroomid是否存在
				int genRoomId = genRoomId();
				while (dao2.get(genRoomId) != null) {
					genRoomId = genRoomId();
				}
				int genRoompwd = genRoompwd();
				UUserRoomInfo ur = new UUserRoomInfo();
				URoomInfo room = new URoomInfo();
				room.setCreateTime(new Date());
				room.setGameId(gameId);
				room.setPassword(genRoompwd);
				room.setRoomId(genRoomId);
				room.setStatus(0);
				room.setUserId(userId);
				dao2.insert(room);
				ur.setCreateTime(new Date());
				ur.setGameId(gameId);
				ur.setRoomId(genRoomId);
				ur.setUserId(userId);
				dao1.insert(ur);

				msg.setRoomId(genRoomId);
				msg.setPassword(genRoompwd);
				msg.setRoomMaster(userId);
				msg.setResult(1);
			}
		}

		//
		GameUser gameUser = GameUser.getGameUser(userId);
		VertxMessageHelper.sendMessageToGateWay(gameUser, msg);
	}

	private int genRoompwd() {
		return RandomUtils.randNum(4);
	}

	private int genRoomId() {
		return RandomUtils.randNum(6);
	}
}
